//
//  UIButton+Timer.m
//  CCExpress
//
//  Created by 崔国冠 on 2018/1/19.
//  Copyright © 2018年 上海崔国冠. All rights reserved.
//

#import "UIButton+Timer.h"

@implementation UIButton (Timer)
#pragma mark - timer
- (void)startTimer {
    __block int timeout = 60; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //没秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setTitle:@"重新获取" forState:UIControlStateNormal];
                self.enabled = YES;
            });
        }else{
            NSString *strTime = [NSString stringWithFormat:@"剩余时间 %ds", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setTitle:strTime forState:UIControlStateNormal];
                self.enabled = NO;
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
@end
